<template>
	<view class="code-container">
		<view @click="getForm" class="vCode-btn">
			{{runTime?`${time}秒后重新获取`: "获取验证码"}}
		</view>
	</view>
</template>

<script>
	export default {
		name:"SendCode",
		props:{
			form:{
				type:Object
			}
		},
		data() {
			return {
				timeId:null,
				time:60,
				runTime: false
			};
		},
		methods:{
			getForm() {
				if(!this.runTime) {
					this.$emit('getForm',this._sendCode)
				}
			},
			async _sendCode(form){
				// 从表单中获取手机号
				const {phone} = await form.validateField(['phone'])
				// 倒计时
				this.timeRunning()
				const result = await this.$http.getCode({phone})
				uni.showToast({
					title: result.msg,
					icon:'none'
				})
				return result.code
			},
			timeRunning() {
				//倒计时定时器 
				this.runTime = true
				if(!this.timeId) {
					this.timeId = setInterval(()=>{
						this.time--
						if(!this.time) {
							this.runTime = false
							clearInterval(this.timeId)
							this.time = 60
							this.timeId = null
						}
					},1000)
				}
			}
		},
		beforeDestroy() {
			this.runTime = false
			clearInterval(this.timeId)
			this.time = 60
			this.timeId = null
		}
	}
</script>

<style lang="scss">
	.code-container {
		flex-shrink: 0;
		margin-right: 20rpx;
		.vCode-btn {
			background-color: $base-color;
			color: #FFFFFF;
			padding: 10rpx;
			border-radius: 10rpx;
			opacity: .8;
		}
	}
</style>
